import React, { useState, useEffect } from 'react';
import axios from 'axios';
import { Bar, Pie } from 'react-chartjs-2';
import { Chart, registerables } from 'chart.js';
import './Dashboard.css';

// 注册Chart.js组件
Chart.register(...registerables);

const AdminDashboard = () => {
  const [stats, setStats] = useState({
    totalUsers: 0,
    totalNotifications: 0,
    unreadNotifications: 0,
    roleDistribution: { admin: 0, payment_manager: 0, employee: 0 }
  });
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  // 获取仪表盘统计数据
  useEffect(() => {
    const fetchDashboardData = async () => {
      try {
        setLoading(true);

        // 获取用户总数
        const usersRes = await axios.get('/users');
        const totalUsers = usersRes.data.length;

        // 获取管理员任务统计
        const notificationStatsRes = await axios.get('/notifications/admin/stats');
        const { totalNotifications, unreadNotifications } = notificationStatsRes.data;

        // 计算角色分布
        const roleDistribution = {
          admin: usersRes.data.filter(u => u.role === 'admin').length,
          payment_manager: usersRes.data.filter(u => u.role === 'payment_manager').length,
          employee: usersRes.data.filter(u => u.role === 'employee').length
        };

        setStats({
          totalUsers,
          totalNotifications,
          unreadNotifications,
          roleDistribution
        });
      } catch (err) {
        console.error('获取仪表盘数据失败', err);
        setError('获取数据失败，请刷新页面重试');
      } finally {
        setLoading(false);
      }
    };

    fetchDashboardData();
  }, []);

  // 角色分布图表数据
  const roleChartData = {
    labels: ['管理员', '清算经理', '员工'],
    datasets: [
      {
        data: [
          stats.roleDistribution.admin,
          stats.roleDistribution.payment_manager,
          stats.roleDistribution.employee
        ],
        backgroundColor: ['#FF6384', '#36A2EB', '#FFCE56'],
        hoverBackgroundColor: ['#FF6384', '#36A2EB', '#FFCE56']
      }
    ]
  };

  // 通知统计图表数据
  const notificationChartData = {
    labels: ['已查收', '未读'],
    datasets: [
      {
        label: '任务状态',
        data: [stats.totalNotifications - stats.unreadNotifications, stats.unreadNotifications],
        backgroundColor: ['#36A2EB', '#FF6384']
      }
    ]
  };

  if (loading) {
    return <div className="dashboard-loading">加载中...</div>;
  }

  if (error) {
    return <div className="dashboard-error">{error}</div>;
  }

  return (
    <div className="dashboard-container">
      <h1 className="dashboard-title">系统概览</h1>

      {/* 统计卡片 */}
      <div className="stats-cards">
        <div className="stat-card">
          <div className="stat-card-content">
            <h3 className="stat-card-title">总用户数</h3>
            <p className="stat-card-value">{stats.totalUsers}</p>
          </div>
        </div>

        <div className="stat-card">
          <div className="stat-card-content">
            <h3 className="stat-card-title">总任务数</h3>
            <p className="stat-card-value">{stats.totalNotifications}</p>
          </div>
        </div>

        <div className="stat-card">
          <div className="stat-card-content">
            <h3 className="stat-card-title">未读任务</h3>
            <p className="stat-card-value">{stats.unreadNotifications}</p>
          </div>
        </div>
      </div>

      {/* 图表区域 */}
      <div className="charts-container">
        <div className="chart-card">
          <h3 className="chart-title">用户角色分布</h3>
          <div className="chart-content">
            <Pie data={roleChartData} options={{ responsive: true, maintainAspectRatio: false }} />
          </div>
        </div>

        <div className="chart-card">
          <h3 className="chart-title">任务状态统计</h3>
          <div className="chart-content">
            <Bar
              data={notificationChartData}
              options={{
                responsive: true,
                maintainAspectRatio: false,
                scales: {
                  y: {
                    beginAtZero: true,
                    ticks: {
                      precision: 0,
                      stepSize: 1
                    }
                  }
                }
              }}
            />
          </div>
        </div>
      </div>
    </div>
  );
};

export default AdminDashboard;